<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use App\Models\SwitchModel;
use App\Models\SwitchPoint;
use Dcat\Admin\Layout\Content;
use Illuminate\Support\Facades\DB;
use App\Handlers\WeconHandler;
use Illuminate\Support\Collection;
use App\Admin\Actions\AllOperation;
use Illuminate\Support\Facades\Redis;

class SwitchChildrenController extends Controller
{
    public function index(Content $content, $pid){
        $switch = SwitchModel::find($pid);
        return $content
            ->header($switch['name'])
            ->description('开关列表')
            ->body($this->grid($pid));
    } 

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid($pid)
    {
        $m = SwitchModel::where('pid', $pid);
        return Grid::make($m, function (Grid $grid) use ($pid) {
            $grid->column('id', 'ID')->sortable();
            $grid->column('name','名称');
            $grid->column('number','编号');
            $grid->column('phase','相数')->using(SwitchModel::PHASE_TEXT);
            $grid->column('level','优先级')->using(SwitchModel::LEVEL_TEXT);
            $grid->column('history',"用电历史")->display(function () {
                $historyUrl = url('admin/switch-history').'/'.$this->id;
                return '<a href="'.$historyUrl.'" target="_blank">历史电量</a>';
            });
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();
            $grid->tools(AllOperation::make(1, 'on')->setKey($pid));
            $grid->tools(AllOperation::make(1, 'off')->setKey($pid));
            $grid->tools(AllOperation::make(2, 'on')->setKey($pid));
            $grid->tools(AllOperation::make(2, 'off')->setKey($pid));
            $grid->tools(AllOperation::make(3, 'on')->setKey($pid));
            $grid->tools(AllOperation::make(3, 'off')->setKey($pid));

            $parent = SwitchModel::find($pid);
            $grid->header(function ($collection) use ($parent) {
                $realtimeUrl = url('admin/switch-realtime').'/'.$parent['project_id'].'/'.$parent['id'];
                return '<div style=\'padding: 10px 10px 10px 150px; font-size:18px;\'><a href="'.$realtimeUrl.'" target="_blank">实时数据</a></div>';
            });
        });
    }

    public function show($pid, $id, Content $content)
    {
        $parent = SwitchModel::find($pid);
        $self = SwitchModel::find($id);
        return $content
            ->translation($self['name'])
            ->title($self['name'])
            ->description($parent['name'])
            ->body($this->detail($id));
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new SwitchModel(), function (Show $show) {
            $show->field('id', 'ID');
            $show->field('name','名称');
            $show->field('number','编号');
            $show->field('phase','相数')->using(SwitchModel::PHASE_TEXT);;
            $show->field('level','优先级')->using(SwitchModel::LEVEL_TEXT);;

            $show->relation('points', '采集点', function ($model) {
                $grid = new Grid(new SwitchPoint);
                $grid->model()->where('switch_id', $model->id);
                // 设置路由
                $grid->setResource('points');
                $grid->column('alias', '采集点编号')->display(function ($alias) {
                    return str_replace('a_', '', $alias);
                });
                $grid->column('name', '采集点名称');
                $grid->disableRefreshButton();
                $grid->disableCreateButton();
                $grid->disableRowSelector();
                $grid->disableActions();
                // $grid->disablePerPages();
                // $grid->simplePaginate(false);
                return $grid;
            });

            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    public function edit($pid, $id, Content $content)
    {
        $parent = SwitchModel::find($pid);
        $self = SwitchModel::find($id);
        return $content
            ->translation($self['name'])
            ->title($self['name'])
            ->description($parent['name'])
            ->body($this->form($pid)->edit($id));
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form($pid = 0)
    {

        $builder = SwitchModel::with('points');
        $parent = SwitchModel::find($pid);
        return Form::make($builder, function (Form $form) use ($parent) {
            $form->text('name', '名称')->required();
            $machineCode = $parent ? $parent['machine_code'] : 0;
            $form->select('number', '编号')->options(SwitchModel::getSwitchNumber($machineCode))->required();
            $form->radio('phase', '相数')->options(SwitchModel::PHASE_TEXT)->required();
            $form->radio('level', '优先级')->options(SwitchModel::LEVEL_TEXT)->required();
            $form->text('address', '地址');
            $pid = $parent ? $parent['id'] : 0;
            $form->hidden('pid')->value($pid);
            $projectId = $parent ? $parent['project_id'] : 0;
            $form->hidden('project_id')->value($projectId);
            $form->hidden('machine_code');

            $form->saving(function (Form $form) {
                if ($form->isCreating()) {
                    $checkNumber = SwitchModel::where('pid', $form->pid)->where('number', $form->number)->first();
                    if ($checkNumber) {
                        return $form->response()->error('该编号下开关已存在');
                    } else {
                        $ssn = SwitchModel::getSsnByParent($form->pid, $form->number);
                        $form->machine_code = $ssn;
                    }
                }
            });

            $form->saved(function (Form $form, $result) {
                if ($form->isCreating() && $form->machine_code) {
                    SwitchPoint::addDefaultPoints($form->getKey());
                }
                if ($form->machine_code) {
                    $pnKey = $form->machine_code.'_p';
                    Redis::set($pnKey, $form->phase);
                }
            });

            $form->deleted(function (Form $form, $result) {
                if ($result) {
                    $data = $form->model()->toArray();
                    SwitchModel::afterDeleted($data[0]['id']);
                }
            });
        });
    }

    public function create(Content $content, $pid){
        return $content
            ->title('新建开关')
            ->description('创建')
            ->body($this->form($pid));
    }

    public function update($pid, $id)
    {
        return $this->form()->update($id);
    }

    public function destroy($pid, $id)
    {
        return $this->form()->destroy($id);
    }
    public function store(){
        return $this->form()->store();
    }
}
